//
//  SkillInfoViewController.m
//  BasketballClub
//
//  Created by 孙鸿吉 on 16/1/8.
//  Copyright © 2016年 孙鸿吉. All rights reserved.
//

#import "SkillInfoViewController.h"
#import "SkillInfoView.h"
#import <UMSocial.h>
#import "SkillHandle.h"
#import <AVOSCloud.h>
#import "RegistViewController.h"
#import "FindPWDViewController.h"
#import "TalkingViewController.h"
@interface SkillInfoViewController ()<UIWebViewDelegate,UIGestureRecognizerDelegate>
{
    NSInteger _differentEventNumber;
}
@end

@implementation SkillInfoViewController
- (void)loadView
{
    self.skillInfoView = [[SkillInfoView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.skillInfoView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"详情";
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = [UIColor cyanColor];
    NSURL *url = [NSURL URLWithString:self.webViewUrl];
    self.skillInfoView.webView.delegate = self;
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.skillInfoView.webView loadRequest:request];
    self.skillInfoView.webView.scalesPageToFit = YES;

    //左侧返回Item
    [self.skillInfoView.leftButton addTarget:self action:@selector(returnSkillVC) forControlEvents:UIControlEventTouchUpInside];
    //右侧收藏Item
    [self.skillInfoView.rightButton addTarget:self action:@selector(collectView) forControlEvents:UIControlEventTouchUpInside];
    //添加手势
    UIScreenEdgePanGestureRecognizer *edgeGR = [[UIScreenEdgePanGestureRecognizer alloc]initWithTarget:self action:@selector(edgeGR)];
    [self.skillInfoView.webView addGestureRecognizer:edgeGR];
    self.skillInfoView.webView.userInteractionEnabled = YES;
    edgeGR.edges = UIRectEdgeLeft;
    edgeGR.delegate = self;
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGR)];
    [self.skillInfoView.loginPresentView addGestureRecognizer:panGR];
    self.skillInfoView.loginPresentView.userInteractionEnabled = YES;
    panGR.delegate = self;
    //分享button
    [self.skillInfoView.shareButton addTarget:self action:@selector(shareOther) forControlEvents:UIControlEventTouchUpInside];
    //分享图片
    self.shareImage = [UIImage imageNamed:@"app"];
    //登陆按钮方法
    [self.skillInfoView.loginButton addTarget:self action:@selector(loginButtonAction) forControlEvents:UIControlEventTouchUpInside];
    //注册按钮方法
    [self.skillInfoView.registButton addTarget:self action:@selector(registButtonAction) forControlEvents:UIControlEventTouchUpInside];
    //忘记密码按钮方法
    [self.skillInfoView.findPWDButton addTarget:self action:@selector(findPWDButtonAction) forControlEvents:UIControlEventTouchUpInside];
    //喜欢按钮方法
    [self.skillInfoView.likeButton addTarget:self action:@selector(likeButtonAction) forControlEvents:UIControlEventTouchUpInside];
    //讨论按钮方法
    [self.skillInfoView.talkButton addTarget:self action:@selector(talkButtonAction) forControlEvents:UIControlEventTouchUpInside];
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCollectState:) name:@"collectState" object:self.skillInfoView.rightButton];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    //喜欢的个数
    AVUser *current = [AVUser currentUser];
    //判断收藏
    //已收藏方法(收藏过得再次进入不在能收藏)
    AVQuery *collectQuery = [AVQuery queryWithClassName:@"celloct"];
    NSString *collectStr = [NSString stringWithFormat:@"collect%ld",self.passValueId];
    [collectQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        if (object != nil) {
            NSString *collectState = [object objectForKey:collectStr];
            if ([collectState isEqualToString:@"isCollect"]) {
                [self.skillInfoView.rightButton setImage:[UIImage imageNamed:@"shoucangle2@2x"] forState:UIControlStateNormal];
                self.skillInfoView.rightButton.userInteractionEnabled = NO;
            }
        }
    }];
    AVQuery *query = [AVQuery queryWithClassName:@"skillLike"];
    NSString *likeCount = [NSString stringWithFormat:@"likeCount%ld",self.passValueId];
    NSString *islike = [NSString stringWithFormat:@"isLike%ld",self.passValueId];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        if (object != nil) {
            NSInteger like = [[object objectForKey:likeCount]integerValue];
            NSString *likeState = [object objectForKey:islike];
            if ([likeState isEqualToString:@"like"] && current != nil) {
                [self.skillInfoView.likeButton setImage:[UIImage imageNamed:@"xihuan2@2x"] forState:UIControlStateNormal];
                self.skillInfoView.likeButton.userInteractionEnabled = NO;
            }
            self.skillInfoView.likeCount.text = [NSString stringWithFormat:@"%ld",like];
            if ([self.skillInfoView.likeCount.text isEqualToString:@"0"]) {
                self.skillInfoView.likeCount.hidden = YES;
            }
        }else{
            NSLog(@"%@",error);
        }
    }];
}
#pragma mark - 通知方法
- (void)changeCollectState:(NSNotification *)sender
{
    [self.skillInfoView.rightButton setImage:[UIImage imageNamed:@"shoucangle2@2x"] forState:UIControlStateNormal];
}
#pragma mark - 登陆按钮方法实现
- (void)loginButtonAction
{
    [AVUser logInWithUsernameInBackground:self.skillInfoView.usernameTF.text password:self.skillInfoView.passwordTF.text block:^(AVUser *user, NSError *error) {
        if (user) {
            if (_differentEventNumber == 1) {
                //收藏方法
                [[NSNotificationCenter defaultCenter] postNotificationName:@"collectState" object:self.skillInfoView.rightButton];
                AVUser *current = [AVUser currentUser];
                NSString *string = [NSString stringWithFormat:@"%@isFirstLogin",current.username];
                NSInteger number = [[LeanCloudService shareService] isFirstLoginWithKey:string];
                if (number == 1) {
                    NSMutableArray *array = [NSMutableArray array];
                    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.webTitle,@"title",self.webViewUrl,@"url", nil];
                    [array addObject:dic];
                    [current setObject:array forKey:@"BasketBall"];
                    [current signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        
                    }];
                    [[LeanCloudService shareService]setIsFirstLoginWithNumber:2 andKye:string];
                    [[LeanCloudService shareService] synchronize];
                }else{
                    NSMutableArray *array = [NSMutableArray array];
                    array = [current objectForKey:@"BasketBall"];
                    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.webTitle,@"title",self.webViewUrl,@"url", nil];
                    [array addObject:dic];
                    [current setObject:array forKey:@"BasketBall"];
                    [current signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        
                    }];
                }
                    //已收藏方法(收藏过得再次进入不在能收藏)
                AVObject *collect = [AVObject objectWithoutDataWithClassName:@"celloct" objectId:@"56a1a8d4128fe1005141c0f0"];
                NSString *collectStr = [NSString stringWithFormat:@"collect%ld",self.passValueId];
                [collect setObject:@"isCollect" forKey:collectStr];
                [collect saveInBackground];
            }else if (_differentEventNumber == 2){
                //执行喜欢方法
            }else{
                //讨论
                TalkingViewController *talkVC = [[TalkingViewController alloc]init];
                talkVC.webID = self.passValueId;
                [self presentViewController:talkVC animated:YES completion:nil];
            }
            [LeanCloudService shareService].nowLoginUserName = self.skillInfoView.usernameTF.text;
            //登陆成功关闭登陆窗口
            self.skillInfoView.usernameTF.text = nil;
            self.skillInfoView.passwordTF.text = nil;
            self.skillInfoView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), SCREEN_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
            //释放响应者
            [self.skillInfoView endEditing:YES];
        }else{
            self.skillInfoView.usernameTF.text = nil;
            self.skillInfoView.passwordTF.text = nil;
            [self loginFiled];
        }
    }];
}
#pragma mark - 注册按钮方法实现
- (void)registButtonAction
{
    RegistViewController *registVC = [[RegistViewController alloc]init];
    [self presentViewController:registVC animated:YES completion:nil];
}
#pragma mark - 忘记密码按钮方法实现
- (void)findPWDButtonAction
{
    FindPWDViewController *findVC = [[FindPWDViewController alloc]init];
    [self presentViewController:findVC animated:YES completion:nil];
}
#pragma mark - 喜欢按钮方法实现
- (void)likeButtonAction
{
    //判断状态
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        [UIView animateWithDuration:0.5 animations:^{
            self.skillInfoView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), 100 * LAYOUT_SIZE_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
        }];
        _differentEventNumber = 2;
    }else{
        [self.skillInfoView.likeButton setImage:[UIImage imageNamed:@"xihuan2@2x"] forState:UIControlStateNormal];
        AVObject *object = [AVObject objectWithoutDataWithClassName:@"skillLike" objectId:@"569ccfc760b23e90721f2c34"];
        NSString *likeCount = [NSString stringWithFormat:@"likeCount%ld",self.passValueId];
        NSString *islike = [NSString stringWithFormat:@"isLike%ld",self.passValueId];
        [object setObject:[NSNumber numberWithInteger:1] forKey:likeCount];
        [object setObject:@"like" forKey:islike];
        [object incrementKey:likeCount];
        [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
            
            }else{
                NSLog(@"%@",error);
            }
        }];
    }
    
}
#pragma mark - 讨论按钮方法实现
- (void)talkButtonAction
{
    //判断状态
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        [UIView animateWithDuration:0.5 animations:^{
            self.skillInfoView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), 100 * LAYOUT_SIZE_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
        }];
        _differentEventNumber = 3;
    }else{
        TalkingViewController *talkVC = [[TalkingViewController alloc]init];
        talkVC.webID = self.passValueId;
        [self presentViewController:talkVC animated:YES completion:nil];
    }
    
}
#pragma mark - 左侧item方法实现
- (void)returnSkillVC
{

    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark - 右侧收藏item方法实现
- (void)collectView
{
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        [UIView animateWithDuration:0.5 animations:^{
            self.skillInfoView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), 100 * LAYOUT_SIZE_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
        }];
        _differentEventNumber = 1;
    }else{
        [self.skillInfoView.rightButton setImage:[UIImage imageNamed:@"shoucangle2@2x"] forState:UIControlStateNormal];
        NSString *string = [NSString stringWithFormat:@"%@isFirstLogin",currentUser.username];
        NSInteger number = [[LeanCloudService shareService] isFirstLoginWithKey:string];
        if (number == 1) {
            NSMutableArray *array = [NSMutableArray array];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.webTitle,@"title",self.webViewUrl,@"url", nil];
            [array addObject:dic];
            [currentUser setObject:array forKey:@"BasketBall"];
            [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
            }];
            [[LeanCloudService shareService] setIsFirstLoginWithNumber:2 andKye:string];
            [[LeanCloudService shareService] synchronize];
        }else{
            NSMutableArray *array = [NSMutableArray array];
            array = [currentUser objectForKey:@"BasketBall"];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.webTitle,@"title",self.webViewUrl,@"url", nil];
            [array addObject:dic];
            [currentUser setObject:array forKey:@"BasketBall"];
            [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
            }];
        }
        //已收藏方法(收藏过得再次进入不在能收藏)
        AVObject *collect = [AVObject objectWithoutDataWithClassName:@"celloct" objectId:@"56a1a8d4128fe1005141c0f0"];
        NSString *collectStr = [NSString stringWithFormat:@"collect%ld",self.passValueId];
        [collect setObject:@"isCollect" forKey:collectStr];
        [collect saveInBackground];
    }
}
#pragma mark - 手势方法实现
- (void)edgeGR
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)panGR
{
    [UIView animateWithDuration:0.5 animations:^{
        self.skillInfoView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), SCREEN_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
    }];
}
#pragma mark - 监控WebView
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        NSString *url = request.URL.absoluteString;
        if (url.length < 100) {
            url = [url substringFromIndex:url.length-9];
            NSString * webUrl = [NSString stringWithFormat:@"http://api.basketball.app887.com/article.html?id=%@",url];
            SkillInfoViewController *secondVC = [[SkillInfoViewController alloc]init];
            UINavigationController *secondNC = [[UINavigationController alloc]initWithRootViewController:secondVC];
            secondVC.webViewUrl = webUrl;
            //初始化之后图片为空 重新赋值
            self.shareImage = [UIImage imageNamed:@"app"];
            //通过捕捉点击webView获取到连接的ID号 通过ID加载数据获取title
            [[SkillHandle shareSkillHandle] loadDataWithWebView:url withBlock:^(BOOL isLoading) {
                if (isLoading) {
                    [self.skillInfoView.webView reloadInputViews];
                }else{
                    NSLog(@"数据请求失败");
                }
            }];
            secondVC.modalTransitionStyle = 1;
            [self presentViewController:secondNC animated:YES completion:nil];

        }else{
            url = [url substringFromIndex:url.length - 1];
            if ([url isEqualToString:@"3"]) {
                //转发微信
                [self shareToWechat];
            }else if ([url isEqualToString:@"2"]){
                //转发朋友圈
                [self shareToWechatFriend];
            }else{
                //转发微博
                [self shareToSina];
            }
        }
        
    }
    return YES;
}
#pragma mark - 界面将要消失方法
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [self.skillInfoView.shareButton addTarget:self action:@selector(shareOther) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 分享按钮方法
- (void)shareOther
{
//切换界面的时候会初始化Controller 所以self.webTitle为空  当为空得时候 加载数据 去除title然后在赋值
    if (self.webTitle == nil) {
        self.webTitle = [SkillHandle shareSkillHandle].WebTitle;
    }
    
    [UMSocialData defaultData].extConfig.qqData.url = self.webViewUrl;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = self.webViewUrl;
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5693101667e58e370a00054f"
                                      shareText:self.webTitle
                                     shareImage:self.shareImage
                                shareToSnsNames:@[UMShareToSina,UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite]
                                       delegate:nil];
}

#pragma mark - 转发微信
- (void)shareToWechat
{
    if (self.webTitle == nil) {
        self.webTitle = [SkillHandle shareSkillHandle].WebTitle;
    }
    [UMSocialData defaultData].extConfig.wechatSessionData.url = self.webViewUrl;
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession] content:self.webTitle image:self.shareImage location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
    
}


#pragma mark - 转发朋友圈
- (void)shareToWechatFriend
{
    if (self.webTitle == nil) {
        self.webTitle = [SkillHandle shareSkillHandle].WebTitle;
    }
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = self.webViewUrl;
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline] content:self.webTitle image:self.shareImage location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
}


#pragma mark - 转发微博
- (void)shareToSina
{
    if (self.webTitle == nil) {
        self.webTitle = [SkillHandle shareSkillHandle].WebTitle;
        
    }
    self.webTitle = [NSString stringWithFormat:@"%@%@",self.webTitle,self.webViewUrl];
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToSina] content:self.webTitle image:self.shareImage location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
}


#pragma mark - 提示框(登录失败)
- (void)loginFiled
{
    CGFloat verison = [[[UIDevice currentDevice]systemVersion]floatValue];
    if (verison >= 8.0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登录失败" message:@"请确认账号和密码是否匹配" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
        
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"登录失败" message:@"请确认账号和密码是否匹配" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [alertView show];
        
        [self performSelector:@selector(aftertimeAction:) withObject:alertView afterDelay:2.0];
    }
    
}

#pragma mark - 延迟2秒方法
- (void)aftertimeAction:(UIAlertView *)sender
{
    [sender dismissWithClickedButtonIndex:0 animated:YES];
    
}



#pragma mark - 处理内存问题

-(void)dealloc {
    
    self.skillInfoView.webView.delegate = nil;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
     [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
    [SkillHandle shareSkillHandle].skillDataArray = nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
